package com.zhentao.datacontrol.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.datacontrol.domain.entity.ResultDetail;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface ResultDetailMapper extends BaseMapper<ResultDetail> {

    /**
     * 分页查询执行结果详情
     */
    @Select("<script>" +
            "SELECT * FROM dc_result_detail " +
            "WHERE execution_id = #{executionId} " +
            "<if test='checkResult != null and checkResult != \"\"'> AND check_result = #{checkResult} </if>" +
            "ORDER BY created_time DESC" +
            "</script>")
    IPage<ResultDetail> selectPageByExecutionId(Page<ResultDetail> page,
                                              @Param("executionId") String executionId,
                                              @Param("checkResult") String checkResult);

    /**
     * 根据执行ID查询结果详情
     */
    @Select("SELECT * FROM dc_result_detail WHERE execution_id = #{executionId} ORDER BY created_time")
    List<ResultDetail> selectByExecutionId(@Param("executionId") String executionId);

    /**
     * 查询错误结果详情
     */
    @Select("SELECT * FROM dc_result_detail " +
            "WHERE execution_id = #{executionId} AND check_result = 'ERROR' " +
            "ORDER BY created_time")
    List<ResultDetail> selectErrorDetails(@Param("executionId") String executionId);

    /**
     * 查询警告结果详情
     */
    @Select("SELECT * FROM dc_result_detail " +
            "WHERE execution_id = #{executionId} AND check_result = 'WARNING' " +
            "ORDER BY created_time")
    List<ResultDetail> selectWarningDetails(@Param("executionId") String executionId);

    /**
     * 统计结果详情
     */
    @Select("SELECT " +
            "check_result, " +
            "COUNT(*) as count " +
            "FROM dc_result_detail " +
            "WHERE execution_id = #{executionId} " +
            "GROUP BY check_result")
    List<ResultDetail> countByCheckResult(@Param("executionId") String executionId);

    /**
     * 清理历史详情记录
     */
    @Select("DELETE FROM dc_result_detail WHERE created_time < #{beforeDate}")
    int cleanDetailsBefore(@Param("beforeDate") String beforeDate);
}
